package com.shengyuan.manage_os.utils;

import android.app.Application;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.shengyuan.manage_os.im.ECApplication;
import com.shengyuan.manage_os.intface.NetResponses;

import org.json.JSONObject;

import java.util.Map;

/**
 * Created by Administrator on 2016/12/19.
 */

public class NetRequest {

    private NetResponses netResponses;
    private String tag;
    private Application context;

    public NetRequest(Application application){
        this.context = application;
    }


    public void setNetResponses(NetResponses netResponses) {
        this.netResponses = netResponses;
    }
    public NetResponses getNetResponses() {
        return netResponses;
    }

    public void request(int method, final String URL, Map map, final String session, String tag, final int type) {

        this.tag = tag;
        JSONObject jsonObject;
        if (map != null)
            jsonObject = new JSONObject(map);
        else {
            jsonObject = null;
        }

        JsonRequest jsonRequest = new JsonObjectRequest(method, URL, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                netResponses.success(type, jsonObject);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                netResponses.fail();
            }
        });
//        {
//            @Override
//            public Map getHeaders() {
//                HashMap headers = new HashMap();
////                headers.put("Accept", "application/json");
////                headers.put("Content-Type", "application/json; charset=UTF-8");
////                if (!"".equals(session))
////                    headers.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + session);
//
//                return headers;
//            }
//        };
        // 设置该请求的标签
        jsonRequest.setTag(tag);
        // 将请求添加到队列中
        System.out.println("@@@@@@@@@@@==========="+context);
        ((ECApplication)context).getRequestQueue().add(jsonRequest);
    }

    public void closeRequest(){
        ((ECApplication)context).getRequestQueue().cancelAll(tag);
    }
}
